﻿using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.IdentityModel.Tokens;
using MyBlog.IService;
using MyBlog.JWT.Utility;
using MyBlog.JWT.Utility.MDFive;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;

namespace MyBlog.JWT.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class AuthoizeController : ControllerBase
    {
        private readonly IWriterInfoService _writerInfoService;

        public AuthoizeController(IWriterInfoService writerInfoService)
        {
            _writerInfoService = writerInfoService;
        }

        [HttpPost("Login")]
        public async Task<ApiResult> Login(string username, string userpwd)
        {
            string pwd = MD5Helper.MD5Encrypt32(userpwd);
            // 数据校验
            var writer = await _writerInfoService.FindAsync(c => c.UserName == username && c.UserPwd == pwd);
            if (writer != null)
            {
                // 登录成功
                var claims = new Claim[]
                {
                    new Claim (ClaimTypes .Name ,writer.Name ),
                    new Claim("Id",writer .Id .ToString ()),
                    new Claim ("UserName",writer .UserName )
                    // 不能存放敏感信息
                };
                var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("SDMC-CJAS1-SAD-DFSFA-SADHJVF-VF"));
                // issuer 代表颁发Token的web应用程序，audience是Token的受理者
                var token = new JwtSecurityToken(
                    issuer: "http://localhost:6060",
                    audience: "http://localhost:5000",
                    claims: claims,
                    notBefore: DateTime.Now,
                    expires: DateTime.Now.AddHours(1),
                    signingCredentials: new SigningCredentials(key, SecurityAlgorithms.HmacSha256)
                    );
                var jwtToken = new JwtSecurityTokenHandler().WriteToken(token);
                return ApiResultHelper.Success(jwtToken);
            }
            else
            {
                return ApiResultHelper.Error("账号或密码错误");
            }
        }
    }
}
